#pragma Once
#include <time.h>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage :" << proc << " serverip serverport" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return -1;
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];

    Sock sockfd;
    sockfd.Socket();
    sockfd.Connect(ip, port);

    const std::string opers = "+-*/%=-=&^";
    srand(time(nullptr));
    int cnt = 5;
    std::string buff_stream;
    while (cnt--)
    {
        std::cout << "------------- 测试开始---cnt: " << cnt << std::endl;
        int x = rand() % 100 + 1;
        int y = rand() % 100;
        usleep(66666);
        char op = opers[rand() % opers.size()];

        std::string content;
        Request req(x, y, op);
        req.Serialize(&content); // 序列化
        content = Encode(content);
        req.Print();
        ssize_t n = write(sockfd.Getfd(), content.c_str(), content.size());
        if (n < 0)
        {
            std::cerr << "write fail" << std::endl;
        }
        // std::cout << "这是最新的发出去的请求 "  << "\n" ;
        // write(sockfd.Getfd(), content.c_str(), content.size());

        char inbuff[1280];
        n = read(sockfd.Getfd(), inbuff, sizeof(inbuff));
        if (n > 0)
        {
            inbuff[n] = 0;
            buff_stream += inbuff;

            std::cout << buff_stream << std::endl;
            std::string info;
            bool r = Decode(buff_stream, &info);
            if (!r)
            {
                break;
            }

            Response res;
            res.Deserialize(info);

            //std::cout << res.result_ << "  " << res.exitcode_ << std::endl;
        }
        else
        {
            break;
        }
        std::cout << "----------------------------------------" << std::endl;
        sleep(1);
    }

    return 0;
}